from flask import Flask, request, jsonify
import json
import logging
import os
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("signal_server.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# 存储接收到的信号
signals = []

@app.route('/receive_signal', methods=['POST'])
def receive_signal():
    """接收聚宽发送的交易信号"""
    try:
        data = request.json
        logger.info(f"收到信号: {data}")
        
        # 添加时间戳
        data['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        # 保存信号
        signals.append(data)
        
        # 保存到文件
        save_signal_to_file(data)
        
        return jsonify({"status": "success", "message": "信号已接收"})
    except Exception as e:
        logger.error(f"处理信号时出错: {str(e)}")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/get_signals', methods=['GET'])
def get_signals():
    """获取所有信号"""
    return jsonify(signals)

def save_signal_to_file(signal):
    """将信号保存到文件"""
    filename = f"signals_{datetime.now().strftime('%Y%m%d')}.json"
    try:
        # 如果文件存在，读取现有数据
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as f:
                existing_data = json.load(f)
        else:
            existing_data = []
        
        # 添加新信号
        existing_data.append(signal)
        
        # 写回文件
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(existing_data, f, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"保存信号到文件时出错: {str(e)}")

if __name__ == '__main__':
    # 确保信号目录存在
    os.makedirs('signals', exist_ok=True)
    
    # 启动服务器，监听所有网络接口
    app.run(host='0.0.0.0', port=5000)